﻿using Bricks;
using Bricks.Injecting;
using System;
using System.Collections.Generic;
using System.Web.Http.Dependencies;

namespace Motar.Web.Http
{

    /// <summary>
    /// 
    /// </summary>
    public class DependencyResolver : FacadeBase<IContainerFacade>, IDependencyResolver
    {

        /// <summary>
        /// 
        /// </summary>
        /// <param name="containerFacade"></param>
        public DependencyResolver(IContainerFacade containerFacade) :
            base(() => containerFacade)
        {
            if (containerFacade == null)
            {
                throw new ArgumentNullException("containerFacade");
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public virtual IDependencyScope BeginScope()
        {
            return this;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="serviceType"></param>
        /// <returns></returns>
        public virtual object GetService(Type serviceType)
        {
            return Execute<object>(
                containerFacade =>
                {
                    object instance;

                    if (containerFacade.TryResolve(serviceType, out instance))
                    {
                        return instance;
                    }
                    else
                    {
                        return null;
                    }
                });
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="serviceType"></param>
        /// <returns></returns>
        public virtual IEnumerable<object> GetServices(Type serviceType)
        {
            return Execute<IEnumerable<object>>(
                containerFacade =>
                {
                    IEnumerable<object> instances;

                    if (containerFacade.TryResolveAll(serviceType, out instances))
                    {
                        return instances;
                    }
                    else
                    {
                        return null;
                    }
                });
        }

        /// <summary>
        /// 
        /// </summary>
        public virtual void Dispose()
        {
        }
    }
}
